import React, { useMemo } from 'react';
import { Modal, Form, Input, InputNumber, TreeSelect, Upload, Button, Row, Col } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { FormInstance } from 'antd/es/form';
import { CallSignatureItem, OrganizationItem } from 'admin/schema/Cas';
import { convertToTree, downLoadByUrl } from '../utils';
import { uploadUrl } from 'admin/servers/servers';
import { useSelector } from 'react-redux';
import { get } from 'lodash';

interface Props {
  visible: boolean;
  title: string;
  onOk: () => void;
  onCancel: () => void;
  form: FormInstance;
  editingSignature: CallSignatureItem | null;
  orgTree: Omit<OrganizationItem, 'children' | 'description'>[];
}

const CallSignatureFormModal: React.FC<Props> = ({
  visible,
  title,
  onOk,
  onCancel,
  form,
  editingSignature,
  orgTree,
}) => {
  const uniqueToken = useSelector((state: any) => state.uniqueToken);
  const userInfo = useSelector((state: any) => state.loginInfo);

  // 使用 useMemo 缓存树形数据转换结果，避免不必要的重复计算
  const treeData = useMemo(() => {
    const treeData = convertToTree(orgTree);
    return treeData;
  }, [orgTree]);

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
      maskClosable={false}
    >
      <Form form={form} layout="vertical">
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="名称"
              name="name"
              rules={[
                { required: true, message: '请输入签名名称' },
                { max: 20, message: '最大长度为20位字符' },
              ]}
            >
              <Input placeholder="请输入签名名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="单位"
              name="organization"
              rules={[{ required: true, message: '请选择单位' }]}
            >
              <TreeSelect
                showSearch
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择单位"
                fieldNames={{ label: 'name', value: 'id' }}
                allowClear
                treeDefaultExpandAll
                treeData={treeData}
                treeNodeFilterProp="title"
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="并发数"
              name="concurrency"
              rules={[{ required: true, message: '请输入并发数' }]}
            >
              <InputNumber min={1} placeholder="请输入并发数" style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="话术场景"
              name="scriptScenario"
              rules={[{ required: true, message: '请上传话术场景文件' }]}
              valuePropName="fileList"
              getValueFromEvent={e => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
              extra={
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <a href="/webapp/模板-智能外呼话术场景.xlsx" target="_blank">
                    模板-智能外呼话术场景.xlsx
                  </a>
                </div>
              }
            >
              <Upload
                name="files"
                action={uploadUrl}
                headers={{
                  uniqueToken,
                  userId: userInfo.id,
                }}
                showUploadList={{
                  showPreviewIcon: false,
                  showDownloadIcon: true,
                }}
                onDownload={(file: any) => {
                  downLoadByUrl(
                    get(file, 'response.data[0].downloadUrl'),
                    get(file, 'response.data[0].realName')
                  );
                }}
              >
                <Button icon={<UploadOutlined />}>上传话术场景</Button>
              </Upload>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="安全承诺书"
              name="securityCommitment"
              rules={[{ required: true, message: '请上传安全承诺书' }]}
              valuePropName="fileList"
              getValueFromEvent={e => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
              extra={
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <a href="/webapp/信息安全承诺书.docx" target="_blank">
                    模版-信息安全承诺书.docx
                  </a>
                </div>
              }
            >
              <Upload
                name="files"
                action={uploadUrl}
                headers={{
                  uniqueToken,
                  userId: userInfo.id,
                }}
                showUploadList={{
                  showPreviewIcon: false,
                  showDownloadIcon: true,
                }}
                onDownload={(file: any) => {
                  downLoadByUrl(
                    get(file, 'response.data[0].downloadUrl'),
                    get(file, 'response.data[0].realName')
                  );
                }}
              >
                <Button icon={<UploadOutlined />}>上传安全承诺书</Button>
              </Upload>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default CallSignatureFormModal;
